/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.BusinessConfig;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.WechatScene;
import com.boxin.ims.modules.wechat.service.BusinessConfigService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatSceneService;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 微信带参数的二维码Controller
 * @author xiaoqian
 * @version 2014-03-18
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/wechatScene")
public class WechatSceneController extends BaseController {

	@Autowired
	private WechatSceneService wechatSceneService;
	
	@Autowired
	private WeChatService weChatService;
	
	
	@Autowired
	private BusinessConfigService businessConfigService;
	

	
	@ModelAttribute
	public WechatScene get(@RequestParam(required=false) Long id) {
		if (id != null){
			return wechatSceneService.get(id);
		}else{
			return new WechatScene();
		}
	}
	
	@RequiresPermissions("wechat:wechatScene:view")
	@RequestMapping(value = {"list", ""})
	public String list(WechatScene wechatScene, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			wechatScene.setUser(user);
		}
        Page<WechatScene> page = wechatSceneService.find(new Page<WechatScene>(request, response), wechatScene); 
        model.addAttribute("page", page);
		return "modules/wechat/wechatSceneList";
	}

	@RequiresPermissions("wechat:wechatScene:view")
	@RequestMapping(value = "form")
	public String form(WechatScene wechatScene, Model model,RedirectAttributes redirectAttributes) {
		
		User user = UserUtils.getUser();
		if (wechatScene.getUser() == null || wechatScene.getUser().getId() <1){
			wechatScene.setUser(user);
		}
		if(!UserUtils.getUser().getInterfaceFlag()){
			model.addAttribute("message", "该功能只限于开通高级接口用户");
		}
		
		List<BusinessConfig>  configList = 	businessConfigService.findAll();
		
		model.addAttribute("wechatScene", wechatScene);
		model.addAttribute("configList", configList);
		return "modules/wechat/wechatSceneForm";
	}

	@RequiresPermissions("wechat:wechatScene:edit")
	@RequestMapping(value = "save")
	public String save(WechatScene wechatScene, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, wechatScene)){
			return form(wechatScene, model, redirectAttributes);
		}
		if(wechatScene.getSceneId()==null){
			Long sceneId=wechatSceneService.getSceneId();
			if(sceneId>100000){
				addMessage(redirectAttributes, "您的场景ID已经用完");
				return "redirect:"+Global.ADMIN_PATH+"/wechat/wechatScene/?repage";
			}
			wechatScene.setSceneId(sceneId);
			System.out.println(sceneId);
		}
		
		if(UserUtils.getUser().getInterfaceFlag()){
			wechatScene.setTicket(getTicket(wechatScene));
			wechatSceneService.save(wechatScene);
			addMessage(redirectAttributes, "保存微信带参数的二维码成功");
		}else{
			addMessage(redirectAttributes, "您没有开通高级接口，该功能无法使用");
		}
		return "redirect:"+Global.ADMIN_PATH+"/wechat/wechatScene/?repage";
	}
	
	@RequiresPermissions("wechat:wechatScene:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		wechatSceneService.delete(id);
		addMessage(redirectAttributes, "删除微信带参数的二维码成功");
		return "redirect:"+Global.ADMIN_PATH+"/modules/wechat/wechatScene/?repage";
	}
	
	
	
	
	
	
	public String getTicket(WechatScene wechatScene){
		User user=UserUtils.getUser();
		WeChat weChat= weChatService.getWeChatByUserId(user.getId());
		String qrcodeparams="";
		JSONObject object = null;
		try {
			String accessToken=TokenUtils.getAPIToken(weChat);
			
			if(wechatScene.getQrcodeType().equals("QR_SCENE")){
				qrcodeparams=WechatInterfaceUtils.createTemporaryQrCodeParams(wechatScene.getExpireSeconds().toString(), wechatScene.getSceneId().toString());
			}else if(wechatScene.getQrcodeType().equals("QR_LIMIT_SCENE")){
				qrcodeparams=WechatInterfaceUtils.createForeverQrCodeParams(wechatScene.getSceneId().toString());
			}
			object=WechatInterfaceUtils.createQrCode(qrcodeparams, accessToken);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object.getString("ticket");
		
	}
	
	

}
